package com.epic.monitor;

import com.epic.daemon.Daemon;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

public class serviceRunner implements RunnerImpl{
    private String service;
    private String start;
    private String stop;
    private String ping;
    private String status;
    private int port;

    private static Logger logger = LogManager.getLogger(Daemon.class);

    public serviceRunner(String service){
        this.service = service;
        this.start = "start";
        this.stop = "stop";
        this.ping = "ping";
        this.status = "start";
        this.port = 10;
    }

    public boolean execCmd(String command) {
        boolean r = true;
        try {
            ProcessBuilder pb = new ProcessBuilder("sh", "-c", command);
            pb.redirectErrorStream(true);
            Process ps = pb.start();
            ProcessOutputThread processOutputThread = new ProcessOutputThread(ps.getInputStream());
            processOutputThread.start();
            int exitVal = ps.waitFor();
            if (exitVal != 0) {
                r = false;
            }

        } catch (Exception e) {
            logger.debug(e.getMessage());
            return false;
        }
        logger.debug("LocalCommandImpl exec done :" + command);
        return r;
    }

    @Override
    public void start() {

    }

    @Override
    public void stop() {

    }


    private final class ProcessOutputThread extends Thread {
//        public final Logger logger = LoggerFactory.getLogger(ProcessOutputThread.class);
        private final  Logger logger = LogManager.getLogger(Daemon.class);
        private InputStream is;

        ProcessOutputThread(InputStream is) {
            this.is = is;
        }

        @Override
        public void run() {
            InputStreamReader ir = null;
            BufferedReader br = null;
            try {
                ir = new InputStreamReader(this.is);
                br = new BufferedReader(ir);
                String output = null;
                while (null != (output = br.readLine())) {
                    logger.info(output);
                }
            } catch (IOException e) {
                logger.debug(e.getMessage());
            } finally {
                try {
                    if (null != br) {
                        br.close();
                    }
                    if (null != ir) {
                        ir.close();
                    }
                    if (null != this.is) {
                        this.is.close();
                    }
                } catch (IOException e) {
                    logger.debug(e.getMessage());
                }
            }
        }
    }

}
